<template>
    <view class="container">
        <!-- Tab Navigation -->
        <view class="tab-nav">
            <view 
                v-for="(tab, index) in tabs" 
                :key="index"
                class="tab-item"
                :class="{ active: currentTab === index }"
                @click="switchTab(index)"
            >
                {{ tab }}
            </view>
            <view class="tab-line" :style="tabLineStyle"></view>
        </view>

        <!-- Order List -->
        <scroll-view scroll-y class="order-list">
            <view v-for="order in filteredOrders" :key="order.id" class="order-item">
                <view class="order-header">
                    <text class="store-name">{{ order.storeName }}</text>
                    <text class="order-status">{{ order.status }}</text>
                </view>

                <!-- 显示订单号 -->
                <view class="order-number-container">
                    <text class="order-number">订单号: {{ order.orderNumber || '暂无' }}</text>
                </view>
                
                <view class="order-content">
                    <view class="product-images">
                        <image 
                            v-for="(item, index) in order.items.slice(0, 2)" 
                            :key="index"
                            :src="`/static/${item.imgUrl}`"
                            mode="aspectFill"
                            class="product-image"
                        ></image>
                    </view>
                    
                    <view class="order-info">
                        <!-- 调整样式，让金额信息靠右显示 -->
                        <view class="order-price-quantity" style="text-align: right;">
                            <text class="price">¥ {{ formatPrice(parseFloat(order.totalAmount)) }}</text>
                            <text class="quantity">共 {{ getTotalQuantity(order) }} 件</text>
                        </view>
                    </view>
                </view>

                <!-- 显示支付时间 -->
                <view class="payment-time-container">
                    <text class="payment-time">支付时间: {{ formatPaymentTime(order.paymentTime) || '暂无' }}</text>
                </view>

                <view class="order-footer">
                    <button 
                        v-if="order.status === '配送中'"
                        class="action-button confirm"
                        @click="confirmReceipt(order)"
                    >
                        确认收货
                    </button>
                    <button 
                        v-if="order.status === '已完成'"
                        class="action-button"
                        @click="deleteOrder(order)"
                    >
                        删除订单
                    </button>
                    <button 
                        v-if="order.status === '已取消'"
                        class="action-button"
                        @click="deleteOrder(order)"
                    >
                        删除订单
                    </button>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script>
import config from '@/config'
export default {
    data() {
        return {
            tabs: ['全部', '进行中', '已完成', '已取消'],
            currentTab: 0,
            orders: []
        }
    },
    computed: {
        tabLineStyle() {
            return {
                transform: `translateX(${this.currentTab * 100}%)`,
                width: `${100 / this.tabs.length}%`
            }
        },
        filteredOrders() {
            switch(this.currentTab) {
                case 0: // 全部
                    return this.orders;
                case 1: // 进行中
                    return this.orders.filter(order => order.status === '配送中');
                case 2: // 已完成
                    return this.orders.filter(order => order.status === '已完成');
                case 3: // 已取消
                    return this.orders.filter(order => order.status === '已取消');
                default:
                    return this.orders;
            }
        }
    },
    onShow() {
        this.loadOrders();
    },
    methods: {
        switchTab(index) {
            this.currentTab = index;
        },
        getTotalQuantity(order) {
            return order.items.reduce((total, item) => total + item.quantity, 0);
        },
        loadOrders() {
            const currentPhone = uni.getStorageSync('currentPhone');
            console.log('当前存储的手机号:', currentPhone);

            uni.request({
                url: config.API+'/users',
                method: 'GET',
                success: (res) => {
                    if (res.statusCode === 200) {
                        console.log('获取到的用户数据:', res.data);
                        const currentUser = res.data.find(user => user.phone === currentPhone);
                        if (currentUser) {
                            // 确保 currentUser.order 是数组类型
                            if (!Array.isArray(currentUser.order)) {
                                currentUser.order = [];
                            }
                            const formattedOrders = currentUser.order.map(order => {
                                // 使用 totalPrice 字段作为总金额
                                let totalAmount = parseFloat(order.totalPrice);
                                if (isNaN(totalAmount)) {
                                    totalAmount = 0;
                                }
                                return {
                                   ...order,
                                    totalAmount,
                                    orderNumber: order.orderNumber || '暂无',
                                    paymentTime: order.paymentTime || '暂无'
                                };
                            });
                            this.orders = formattedOrders;
                        } else {
                            console.error('未找到匹配手机号的用户:', currentPhone);
                        }
                    } else {
                        console.error('获取用户数据失败. 状态码:', res.statusCode);
                    }
                },
                fail: (err) => {
                    console.error('获取订单数据失败:', err);
                }
            });
        },
        confirmReceipt(order) {
            const currentPhone = uni.getStorageSync('currentPhone');
            
            uni.showModal({
                title: '确认收货',
                content: '确认已收到商品？',
                success: (res) => {
                    if (res.confirm) {
                        // Update order status
                        const updatedOrder = { ...order, status: '已完成' };
                        const updatedOrders = this.orders.map(o => 
                            o.id === order.id ? updatedOrder : o
                        );
                        
                        // Get current user
                        uni.request({
                            url: config.API+'/users',
                            method: 'GET',
                            success: (res) => {
                                if (res.statusCode === 200) {
                                    const currentUser = res.data.find(user => user.phone === currentPhone);
                                    if (currentUser) {
                                        // 确保 currentUser.order 是数组类型
                                        if (!Array.isArray(currentUser.order)) {
                                            currentUser.order = [];
                                        }
                                        // Update user's orders
                                        const updatedUser = {
                                            ...currentUser,
                                            order: updatedOrders
                                        };
                                        
                                        // Send update request
                                        uni.request({
                                            url: config.API+`/users/${currentUser.id}`,
                                            method: 'PUT',
                                            data: updatedUser,
                                            success: (updateRes) => {
                                                if (updateRes.statusCode === 200) {
                                                    this.orders = updatedOrders;
                                                    uni.showToast({
                                                        title: '确认收货成功',
                                                        icon: 'success'
                                                    });
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        });
                    }
                }
            });
        },
        deleteOrder(order) {
            const currentPhone = uni.getStorageSync('currentPhone');
            
            uni.showModal({
                title: '删除订单',
                content: '确认要删除该订单吗？',
                success: (res) => {
                    if (res.confirm) {
                        // Remove order from list
                        const updatedOrders = this.orders.filter(o => o.id !== order.id);
                        
                        // Get current user
                        uni.request({
                            url: config.API+'/users',
                            method: 'GET',
                            success: (res) => {
                                if (res.statusCode === 200) {
                                    const currentUser = res.data.find(user => user.phone === currentPhone);
                                    if (currentUser) {
                                        // 确保 currentUser.order 是数组类型
                                        if (!Array.isArray(currentUser.order)) {
                                            currentUser.order = [];
                                        }
                                        // Update user's orders
                                        const updatedUser = {
                                            ...currentUser,
                                            order: updatedOrders
                                        };
                                        
                                        // Send update request
                                        uni.request({
                                            url: config.API+`/users/${currentUser.id}`,
                                            method: 'PUT',
                                            data: updatedUser,
                                            success: (updateRes) => {
                                                if (updateRes.statusCode === 200) {
                                                    this.orders = updatedOrders;
                                                    uni.showToast({
                                                        title: '删除成功',
                                                        icon: 'success'
                                                    });
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        });
                    }
                }
            });
        },
        formatPrice(price) {
            return price.toFixed(2);
        },
        formatPaymentTime(time) {
            if (time === '暂无') return time;
            const date = new Date(time);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
    }
}
</script>

<style scoped>
.container {
    min-height: 100vh;
    background-color: #f8f8f8;
}

.tab-nav {
    display: flex;
    background-color: #fff;
    position: relative;
    border-bottom: 1rpx solid #eee;
}

.tab-item {
    flex: 1;
    text-align: center;
    padding: 30rpx 0;
    font-size: 28rpx;
    color: #666;
}

.tab-item.active {
    color: #0099FF;
    font-weight: 500;
}

.tab-line {
    position: absolute;
    bottom: 0;
    height: 4rpx;
    background-color: #0099FF;
    transition: transform 0.3s;
}

.order-list {
    height: calc(100vh - 94rpx);
}

.order-item {
    margin: 20rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #eee;
}

.store-name {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

.order-status {
    font-size: 26rpx;
    color: #0099FF;
}

.order-number-container {
    padding: 10rpx 0;
    color: #666;
    font-size: 24rpx;
}

.order-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
}

.product-images {
    display: flex;
    gap: 10rpx;
}

.product-image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
}

.order-info {
    display: flex;
    justify-content: space-between;
    width: 100%;
}

/* 新增的样式类，用于调整金额信息的位置 */
.order-price-quantity {
    width: 100%;
}

.price {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 10rpx;
    display: block;
}

.quantity {
    font-size: 24rpx;
    color: #999;
}

.payment-time-container {
    padding: 10rpx 0;
    color: #666;
    font-size: 24rpx;
}

.order-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 20rpx;
    border-top: 1rpx solid #eee;
    gap: 20rpx;
}

.action-button {
    font-size: 24rpx;
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    background-color: #fff;
    border: 1rpx solid #ddd;
    color: #666;
    margin: 0;
}

.action-button.confirm {
    background-color: #0099FF;
    color: #fff;
    border: none;
}
</style>    